package _7_io_socket_http.web_container;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Paths;

public class HttpServer {


  public static void main(String... args) {
    HttpServer server = new HttpServer();
    server.await();
  }

  // 存放静态资源的位置
  public static final String WEB_ROOT = Paths.get(System.getProperty("user.dir"), "webroot").toString();

  // 关闭Server的请求
  private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";

  // 是否关闭Server
  private boolean shutdown = false;

  private void await() {

    // 启动 ServerSocket
    int port = 8081;
    try (ServerSocket serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));) {
      while (!shutdown) {
        try (Socket socket = serverSocket.accept();
            InputStream input = socket.getInputStream();
            OutputStream output = socket.getOutputStream();) {
          // 创建socket

          // 封装input至request, 并处理请求
          Request request = new Request(input);
          request.parse();

          // 封装output至response
          Response response = new Response(output);
          response.setRequest(request);
          response.sendStaticResource();

          // 关闭socket
          socket.close();

          // 如果接受的是关闭请求，则设置关闭监听request的标志
          shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }

    // 循环等待一个Request请求
  }
}
